<?php
/***********************************************************
 * 后台公共管理
 * @作者 pcfcms <1131680521@qq.com>
 * @版权 广州市春风科技有限公司
 * @主页 http://www.pcfcms.com
 * @时间 2019年12月21日
***********************************************************/
namespace app\admin\controller;
use think\facade\Db;
use think\facade\Request;
use think\facade\Session;
use think\facade\Console;
use think\facade\Cache;
use think\facade\Cookie;
class Index extends Base
{
    // 后台首页
    public function index()
    {
        //后台模块导航
        $getMenu = Cache::get('getMenuglobal');
        if(!$getMenu){
            $getMenu = Db::name('menu')->where(['parent_id' => 0,'is_show' => 1,'status'=>1])->order('id asc')->select()->toArray();
            cache::set('getMenuglobal',$getMenu,PCFCMS_CACHE_TIME);//后台模块导航缓存
        }
        $this->assign('getMenu',$getMenu);
        //后台左侧导航
        $this->assign('leftmenu',getMenuList());
        //登录后台账号显示
        $this->assign('pcfadmin_info', getAdminInfo(session::get('admin_id')));
        return $this->fetch();
    }

    // 系统首页
    public function main()
    {
        $globalConfig = tpCache('global');
        // 服务器信息
        $this->assign('sys_info',$this->get_sys_info($globalConfig));
        // 升级弹窗
        $this->assign('web_show_popup_upgrade', tpCache('web.web_show_popup_upgrade'));
        // 纠正上传附件的大小，始终以空间大小为准
        $file_size = isset($globalConfig['file_size']) ? $globalConfig['file_size'] :'';
        $maxFileupload = @ini_get('file_uploads') ? ini_get('upload_max_filesize') : 0;
        $maxFileupload = intval($maxFileupload);
        if (empty($file_size) || $file_size > $maxFileupload) {
            tpCache('basic', ['file_size'=>$maxFileupload]);
        }
        // 同步导航与内容统计的状态
        $this->syn_open_quickmenu();
        // 快捷导航
        $quickMenu = Db::name('quickentry')->where(['type' => 1,'checked' => 1,'status' => 1])->order('sort_order asc, id asc')->select()->toArray();
        $this->assign('quickMenu',$quickMenu);
        // 最近登录
        if(Session::get('admin_id') != 1 && Session::get('admin_info.role_id') > 0){
            $adminlog = Db::name('admin_log')->field('log_info,log_ip,log_time,admin_id')->where('admin_id',Session::get('admin_id'))->limit(11)->order('log_id desc')->select()->toArray();
        }else{
            $adminlog = Db::name('admin_log')->field('log_info,log_ip,log_time,admin_id')->limit(11)->order('log_id desc')->select()->toArray();
        }

        foreach ($adminlog as $key => $value) {
            $adminlog[$key]['log_time'] = pcftime($value['log_time']);
            $adminlog[$key]['adminname'] = Db::name('admin')->where('admin_id', $value['admin_id'])->value('user_name');
            unset($adminlog[$key]['admin_id']);
        }
        $this->assign('adminlog',$adminlog);
        return $this->fetch();
    }

    // 快捷导航管理
    public function ajax_quickmenu()
    {
        $domain = Request::baseFile().'/index/main';
        $result = ['status' => false,'msg' => '失败','data' => '','url'=>''];
        if (Request::isAjax()) {
            $checkedids = input('post.checkedids/a', []);
            $ids = input('post.ids/a', []);
            $saveData = [];
            foreach ($ids as $key => $val) {
                if (in_array($val, $checkedids)) {
                    $checked = 1;
                } else {
                    $checked = 0;
                }
                $saveData[$key] = [
                    'id'            => $val,
                    'checked'       => $checked,
                    'sort_order'    => intval($key) + 1,
                    'update_time'   => getTime(),
                ];
            }
            if (!empty($saveData)) {
                foreach ($saveData as $key => $value) {
                    Db::name('quickentry')->where('id', $value['id'])->update($value);
                }
                $result['status'] = true;
                $result['msg']    = '操作成功';
                $result['url']    = $domain;
                return $result;
            }
            $result['status'] = false;
            $result['msg']    = '操作失败';
            return $result;
        }
        $menuList = Db::name('quickentry')->where([
                'type'      => 1,
                'groups'    => 0,
                'status'    => 1,
            ])->order('sort_order asc, id asc')->select()->toArray();
        $this->assign('menuList',$menuList);
        return $this->fetch();
    }

    // 同步受开关控制的导航和内容统计
    private function syn_open_quickmenu()
    {
        //处理模型导航和统计
        $updateData = [];
        $channeltypeRow = Db::name('channel_type')->cache(true,PCFCMS_CACHE_TIME,"channeltype")->select()->toArray();
        foreach ($channeltypeRow as $key => $val) {
            $updateData[] = [
                'groups'    => 1,
                'vars'  => 'channel='.$val['id'],
                'status'    => $val['status'],
                'update_time'   => getTime(),
            ];
        }
        if(!empty($updateData)){
            foreach ($updateData as $key => $value) {
                Db::name('quickentry')->where('vars', $value['vars'])->update($value);
            }
        }
    }

    // ajax 修改指定表数据字段  一般修改状态 比如 是否推荐 是否开启 等 图标切换的
    public function changeTableVal()
    {
        if (Request::isAjax()) {
            $url = null;
            $data = ['refresh'=> 0];
            $param = input('param.');
            $table    = input('param.table/s'); // 表名
            $id_name  = input('param.id_name/s'); // 表主键id名
            $id_value = input('param.id_value/d'); // 表主键id值
            $field    = input('param.field/s'); // 修改哪个字段
            $value    = input('param.value/s', '', null); // 修改字段值
            $value    = eyPreventShell($value) ? $value : strip_sql($value);
            //验证权限
            if(isset($param['act'])){
                $ctl_act    = $param['act'];
                $popedom = appfile_popedom($ctl_act);
                if(!$popedom["status"]){
                    if(config('params.auth_msg.test')){
                        $result = ['status' => false, 'msg' => config('params.auth_msg.pcfcms')];
                        return $result;
                    }else{
                        $result = ['status' => false, 'msg' => config('params.auth_msg.status')];
                        return $result;                    
                    }
                }
            }
            unset($param['act']);
            //处理数据的安全性
            if (empty($id_value)) {
                $result = ['status' => false, 'msg' => '查询条件id不合法！'];
                return $result;
            }
            foreach ($param as $key => $val) {
                if ('value' == $key) {continue;}
                if (!preg_match('/^([A-Za-z0-9_-]*)$/i', $val)) {
                    $result = ['status' => false, 'msg' => '数据含有非法入侵字符！'];
                    return $result;
                }
            }
            $savedata = [$field => $value,'update_time' => getTime(),];
            Db::name($table)->where("$id_name = $id_value")->save($savedata);//根据条件保存修改的数据
            Cache::clear('getmenu');
            $result = ['status' => true, 'msg' => '更新成功', 'data' => $data, 'url' => $url];
            return $result;
        }
    }

    // 百度推送
    public function bdTableVal()
    {
        if (Request::isAjax()) {
            $param = input('param.baiduurl');
            $result = BaiduPush($param);
        }
    }

    // 系统信息
    private function get_sys_info($globalConfig = [])
    {
        $sys_info['os']             = PHP_OS;
        $sys_info['zlib']           = function_exists('gzclose') ? 'YES' : '<font color="red">NO（请开启 php.ini 中的php-zlib扩展）</font>';
        $sys_info['safe_mode']      = (boolean) ini_get('safe_mode') ? 'YES' : 'NO';    
        $sys_info['timezone']       = function_exists("date_default_timezone_get") ? date_default_timezone_get() : "no_timezone";
        $sys_info['curl']           = function_exists('curl_init') ? 'YES' : '<font color="red">NO（请开启 php.ini 中的php-curl扩展）</font>';  
        $sys_info['web_server']     = $_SERVER['SERVER_SOFTWARE'];
        $sys_info['phpv']           = phpversion();
        $sys_info['ip']             = serverIP();
        $sys_info['postsize']       = @ini_get('file_uploads') ? ini_get('post_max_size') :'unknown';
        $sys_info['fileupload']     = @ini_get('file_uploads') ? ini_get('upload_max_filesize') :'unknown';
        $sys_info['max_ex_time']    = @ini_get("max_execution_time").'s'; //脚本最大执行时间
        $sys_info['set_time_limit'] = function_exists("set_time_limit") ? true : false;
        $sys_info['domain']         = $_SERVER['HTTP_HOST'];
        $sys_info['memory_limit']   = ini_get('memory_limit');
        //$sys_info['version']        = file_get_contents(root_path().'extend/conf/version.txt');
        $mysqlinfo = Db::query("SELECT VERSION() as version");
        $sys_info['mysql_version']  = $mysqlinfo[0]['version'];
        if(function_exists("gd_info")){
            $gd = gd_info();
            $sys_info['gdinfo']     = $gd['GD Version'];
        }else {
            $sys_info['gdinfo']     = "未知";
        }
        if (extension_loaded('zip')) {
            $sys_info['zip']     = "YES";
        } else {
            $sys_info['zip']     = '<font color="red">NO（请开启 php.ini 中的php-zip扩展）</font>';
        }
        $sys_info['curent_version'] = getCmsVersion();//获取程序版本
        $sys_info['web_name'] = "PCFCMS系统";
        return $sys_info;
    }

    // 清除整站全部缓存
    public function clearCache()
    {
        if (!function_exists('unlink')) {
            $result = ['status' => 0, 'msg' => 'php.ini未开启unlink函数，请联系空间商处理！','url'=>''];
            return json($result);
        }
        // 兼容每个用户的自定义字段，重新生成数据表字段缓存文件
        $systemTables = ['arctype'];
        $data = Db::name('channel_type')->column('table');
        $tables = array_merge($systemTables, $data);
        foreach ($tables as $key => $table) {
            if ('arctype' != $table) {
                $table = $table.'_content';
            }
            try {
                schemaTable($table);
            } catch (\Exception $e) {}
        }
        Cache::clear();//清除数据缓存文件
        $admin_temp = glob(ROOT_PATH.'runtime/admin/temp/'. '*.php');//清除后台临时文件缓存
        array_map('unlink', $admin_temp);
        $home_temp = glob(ROOT_PATH.'runtime/home/temp/' . '*.php');//清除前台临时文件缓存
        array_map('unlink', $home_temp);
        $api_temp = glob(ROOT_PATH.'runtime/api/temp/'. '*.php');//清除API临时文件缓存
        array_map('unlink', $api_temp);
        $result = ['status' => 1, 'msg' => '清除缓存成功' ,'url'=> Request::baseFile()];
        return $result;
    }

    // 录入商业授权
    public function authortoken()
    {
        $domain = config('params.service_pcf');
        $domain = base64_decode($domain);
        $vaules = array(
            'cms_type'  => 1,
            'client_domain' => urldecode(request::host(true)),
        );
        $result = ['status' => false, 'msg' => '验证授权失败'];
        return $result;
    }

    // 授权
    public function ajax_sq(){
        if (Request::isAjax()) {
            $param['web_is_authortoken'] = 1;
            tpCache('web',$param);
            Cache::clear();//清除数据缓存文件
            $admin_temp = glob(ROOT_PATH.'runtime/admin/temp/'. '*.php');//清除后台临时文件缓存
            array_map('unlink', $admin_temp);
            $home_temp = glob(ROOT_PATH.'runtime/home/temp/' . '*.php');//清除前台临时文件缓存
            array_map('unlink', $home_temp);
            $api_temp = glob(ROOT_PATH.'runtime/api/temp/'. '*.php');//清除API临时文件缓存
            array_map('unlink', $api_temp);
        }
    }
    
    // 文档处理显示页面
    public function uphtml()
    {
        //防止php超时
        function_exists('set_time_limit') && set_time_limit(0);
        $assign_data = array();
        $post = $_GET;
        if(isset($post['typeid']) && $post['typeid']>0){
            $post['typeid'] = $post['typeid'];
        }else{
            $post['typeid'] = 0;
        }
        $assign_data['data'] = $post;
        $row = Db::name('archives')
            ->field("b.*, a.*, a.aid as aid, c.ifsystem,c.ctl_name")
            ->alias('a')
            ->join('arctype b', 'a.typeid = b.id', 'LEFT')
            ->join('channel_type c', 'c.id = a.channel', 'LEFT')
            ->where('a.aid', '=', $post['aid'])
            ->find();
        $assign_data['arcurl'] = get_arcurl($row); // 查看前端内容
        $assign_data['channel'] = $row['channel']; // 频道ID
        $assign_data['seo_pseudo'] = tpCache('seo.seo_pseudo'); // URL配置规则
        if($post['pcfcms']){
            if($row['ifsystem'] && 1== $row['ifsystem']){
                $assign_data['listurl'] = url('/Article/index', ['typeid'=>$post['typeid'],'channel'=>$row['channel']])->suffix(true)->domain(true)->build();         
            }else{
                $assign_data['listurl'] = url('/Custom/index', ['typeid'=>$post['typeid'],'channel'=>$row['channel']])->suffix(true)->domain(true)->build();
            }
        }else{
            if($row['ifsystem'] && 1== $row['ifsystem']){
                $assign_data['listurl'] = url('/Content/index', ['channel'=>$row['channel']])->suffix(true)->domain(true)->build();          
            }else{
                $assign_data['listurl'] = url('/Content/index', ['typeid'=>$post['typeid'],'channel'=>$row['channel']])->suffix(true)->domain(true)->build();
            }            
        }
        $assign_data['env_is_uphtml'] = Cookie::get('ENV_IS_UPHTML'); // 判断是否生成成功
        $action_name = $post['action'];
        $assign_data['ctl_name'] = $row['ctl_name'];
        if ('add' == $action_name) {
            $assign_data['msg'] = '发布';
            $assign_data['msg1'] = '继续发布';
        } else {
            $assign_data['msg'] = '编辑';
            $assign_data['msg1'] = '发布';
        }
        $this->assign($assign_data);
        return $this->fetch();
    }

}